/* This code was Started by Dr. Kohl for the PIC 18F25k22
 * Nathaniel Bond will be the primary author of this code
 */

#include "powerhouse.h"
#include "peripherals.h"

#pragma config FOSC = INTIO67, PLLCFG = OFF, PRICLKEN = ON,FCMEN = ON, PWRTEN = OFF
#pragma config BOREN = SBORDIS, BORV = 250, WDTEN = OFF, WDTPS = 4096, PBADEN = OFF
#pragma config HFOFST = OFF, MCLRE = EXTMCLR, STVREN = ON, LVP = OFF, DEBUG = ON

unsigned char counter; //counter variable to count
                       //the number of TMR0 overflows

// http://ww1.microchip.com/downloads/en/DeviceDoc/51702a.pdf
void interrupt Timer0_ISR(void) {
    if (T0IE && T0IF) //are TMR0 interrupts enabled and
                      //is the TMR0 interrupt flag set?
    {
        T0IF = 0;  //TMR0 interrupt flag must be cleared in software
                   //to allow subsequent interrupts
        if (++counter > 19) { // 5 secs per check * 1e6 cycles/sec / 4 cycles/inst / 2^16 counts per overflow
            counter = 0;
            ADCON0bits.GODONE = 1;
            setLowBattOn();
            // Delay10KTCYx(10);
            while (ADCON0bits.GODONE);
            unsigned int result = (unsigned int) ReadADC();
            //double voltage = (result * 4.096) / 1024;
            if (result > 725) { // computes to 2.9 V; corrected for real 2.4 V
                setLowBattOff();
            }
        }
    }
}

void main(void) {
    unsigned char data, 
                  i = 0;

    init();

    while (1) {
        data = SPI();
        //T0IE = 0; // don't service interrupts until this instruction is executed
        idEx(data);
        //T0IE = 1;
    }
}
